package com.ueboot.weishop.service.shiro.impl;


import com.ueboot.core.shiro.ShiroService;
import com.ueboot.core.utils.MD5Util;
import com.ueboot.weishop.entity.role.Resources;
import com.ueboot.weishop.entity.role.Role;
import com.ueboot.weishop.entity.role.User;
import com.ueboot.weishop.repository.role.PermissionRepository;
import com.ueboot.weishop.repository.role.UserRepository;
import com.ueboot.weishop.repository.role.UserRoleRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Slf4j
@Service
public class ShiroServiceImpl implements ShiroService {

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private UserRoleRepository userRoleRepository;


    @Autowired
    private PermissionRepository permissionRepository;



    @Override
    public boolean userExist(String username, String password) {
        password = MD5Util.MD5Encode(password.toLowerCase(),"UTF-8");
        User user = this.userRepository.findByUsernameAndPassword(username,password);
        return user!=null;
    }

    @Override
    public boolean isPassed(String username, String password) {
        return false;
    }

    @Override
    public Set<String> getUserRoleNames(String username) {
        List<Role> roles = this.userRoleRepository.findByUsername(username);

        Set<String> names = new HashSet<>();
        for (Role role : roles) {
            names.add(role.getRole());
        }

        return names;
    }

    @Override
    public Set<String> getUserPermission(String username) {
        return new HashSet<>();
    }

    @Override
    public List<String> getRolePermission(String role) {

        List<Resources> resources = this.permissionRepository.findByRole(role);

        List<String> names = new ArrayList<>();
        for(Resources resource : resources) {
            names.add(resource.getPermission());
        }
        return names;
    }

}
